package com.robam.common.exception;

import com.robam.common.utils.R;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 *  全局异常处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @ExceptionHandler(value= MethodArgumentNotValidException.class)
    public R handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        logger.error(e.getMessage(), e);
        e.printStackTrace();
        return R.error(BizCodeEnum.ValidException.getCode(), BizCodeEnum.ValidException.getMsg());
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public R handlerNoFoundException(Exception e) {
        logger.error(e.getMessage(), e);
        e.printStackTrace();
        return R.error(BizCodeEnum.PathException.getCode(), BizCodeEnum.PathException.getMsg());
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public R handleDuplicateKeyException(DuplicateKeyException e){
        logger.error(e.getMessage(), e);
        e.printStackTrace();
        return R.error(BizCodeEnum.DuplicateKeyException.getCode(), BizCodeEnum.DuplicateKeyException.getMsg());
    }

    @ExceptionHandler(AuthorizationException.class)
    public R handleAuthorizationException(AuthorizationException e){
        logger.error(e.getMessage(), e);
        e.printStackTrace();
        return R.error(BizCodeEnum.AuthorizationException.getCode(), BizCodeEnum.AuthorizationException.getMsg());
    }

    /**
     * 项目自定义异常
     * @param e 异常对象
     * @return
     */
    @ExceptionHandler(GulimallException.class)
    public R handleGulimallException(GulimallException e) {
        logger.error(e.getMessage(), e);
        e.printStackTrace();
        return R.error(e.getCode(), e.getMsg());
    }


    /**
     * 通用异常
     * @param e 异常对象
     * @return
     */
    @ExceptionHandler(Exception.class)
    public R handleException(Exception e){
        logger.error(e.getMessage(), e);
        e.printStackTrace();
        return R.error();
    }

}
